package com.yanfan.modbus.model;


import com.yanfan.modbus.ModbusUtils;
import com.yanfan.modbus.frame.abs.ModbusFrame;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @author oliver foo
 * @description
 * @date 2022/3/16 8:35
 */
public class ModbusTcpMessage extends ModbusMessage {
    protected final int transactionId;

    public ModbusTcpMessage(ModbusFrame modbusFrame, int transactionId) {
        super(modbusFrame);
        this.transactionId = transactionId;
    }


    public int getTransactionId() {
        return transactionId;
    }

    @Override
    public void getMessageData(ByteBuf buf) {
        ByteBuf frameBuf = Unpooled.buffer();
        // Write the particular message.
        modbusFrame.write(frameBuf);

        int messageLength = frameBuf.readableBytes();

        // Create the XA message
        buf.writeShort(transactionId);
        buf.writeShort(ModbusUtils.MODBUS_TCP_PROTOCOL_ID);
        buf.writeShort(messageLength);

        buf.writeBytes(frameBuf);
        frameBuf.release();

        buf.discardReadBytes();
    }


}
